<?php
namespace Acme\DomotiqueBundle\Modele;

class Thermostat
{

	private $piece;
	private $eco;
	private $confort;
	protected $manuel;

	private $programme;

	public function __construct($piece)
	{
		$json = json_decode(file_get_contents(dirname(__FILE__)."/saved/thermostat_".$piece.".json"));
		$this->eco = $json->eco;
		$this->confort = $json->confort;
		$this->programme = $json->programme;
		$this->piece = $json->piece;
		$this->manuel = $json->manuel;
		$this->current = $json->current;

	}
	public function getManuel()
	{
		return $this->manuel;
	}
	public function set($type, $temperature)
	{
		$this->$type = (int) $temperature;
	}
	public function setCurrent($type, $value)
	{
		$this->current->$type = $value;
	}

	/** 
	  * @TODO 
	  **/
	public function check()
	{
		return true;
	}
	public function getTemp()
	{
		$now = time();
		foreach($this->programme as $horaire=>$type){
			list($from,$to) = explode("-",$horaire);
			list($from_h, $from_min) = explode(":",$from);
			list($to_h, $to_min) = explode(":",$to);

			$start = mktime($from_h,$from_min,0,date("m"),date("d"),date("Y"));
			$end = mktime($to_h,$to_min,0,date("m"),date("d"),date("Y"));

			if($start <= $now && $end > $now){
				return $this->$type;
			}
		}
		return false;
	}

	public function getType()
	{
		$now = time();
		foreach($this->programme as $horaire=>$type){
			list($from,$to) = explode("-",$horaire);
			list($from_h, $from_min) = explode(":",$from);
			list($to_h, $to_min) = explode(":",$to);

			$start = mktime($from_h,$from_min,0,date("m"),date("d"),date("Y"));
			$end = mktime($to_h,$to_min,0,date("m"),date("d"),date("Y"));

			if($start <= $now && $end > $now){
				return $type;
			}
		}
		return false;
	}

	public function save()
	{
		$json = json_encode(array(
			"piece" => $this->piece,
			"eco" => $this->eco,
			"confort" => $this->confort,
			"manuel" => $this->manuel,
			"programme" => $this->programme, 
			"current" => $this->current
		), JSON_PRETTY_PRINT);
		file_put_contents(dirname(__FILE__)."/saved/thermostat_".$this->piece.".json", $json);
		return true;
	}

}
